Two Sum
August 17, 2016
A pretty straightforward solution. Use a HashMap with the key representing the
(target-nums[i])
and the value representing the index at which it appeared.
Full Solution in Java:
public class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> values = new HashMap<Integer,Integer>(); int[] retArr = new int[2]; for(int i=0; i<nums.length; i++){ if(values.containsKey(nums[i])){ retArr[0] = values.get(nums[i]); retArr[1] = i; break; } else{ values.put(target-nums[i], i); } } return retArr; } }